package com.bestcem.xm.txtanls.dao.impl;//package com.bestcem.xm.txtanls.dao.impl;
//
//import cn.hutool.core.collection.CollUtil;
//import cn.hutool.core.lang.Validator;
//import cn.hutool.core.util.ObjectUtil;
//import com.bestcem.xm.txtanls.dao.RecordDao;
//import com.bestcem.xm.txtanls.dao.dto.PageDTO;
//import com.bestcem.xm.txtanls.dao.dto.RecordSentiDTO;
//import com.bestcem.xm.txtanls.entity.pojo.RecordDO;
//import com.bestcem.xm.txtanls.grpc.service.param.PageParam;
//import com.bestcem.xm.txtanls.service.dto.RecordSearchDTO;
//import com.bestcem.xm.txtanls.service.dto.chart.PeriodTimeDTO;
//import com.bestcem.xm.txtanls.service.dto.record.PageRecordDTO;
//import com.bestcem.xm.util.CommonUtils;
//import com.bestcem.xm.common.core.uitls.DateUtil;
//import com.mongodb.client.result.DeleteResult;
//import org.bson.types.ObjectId;
//import org.springframework.data.domain.Sort;
//import org.springframework.data.mongodb.core.MongoTemplate;
//import org.springframework.data.mongodb.core.aggregation.Aggregation;
//import org.springframework.data.mongodb.core.aggregation.AggregationResults;
//import org.springframework.data.mongodb.core.aggregation.GroupOperation;
//import org.springframework.data.mongodb.core.aggregation.MatchOperation;
//import org.springframework.data.mongodb.core.query.Criteria;
//import org.springframework.data.mongodb.core.query.Query;
//import org.springframework.stereotype.Repository;
//import org.springframework.util.CollectionUtils;
//import org.springframework.util.ObjectUtils;
//
//import javax.annotation.Resource;
//import java.time.LocalDate;
//import java.time.LocalDateTime;
//import java.time.LocalTime;
//import java.util.*;
//import java.util.stream.Collectors;
//
//import static com.bestcem.xm.txtanls.util.CollectionName.TXTANLS_RECORD;
//import static com.bestcem.xm.txtanls.util.ColumnConstant.Base._ID;
//import static com.bestcem.xm.txtanls.util.ColumnConstant.RecordDO.*;
//import static com.bestcem.xm.txtanls.util.Constants.OR;
//import static com.bestcem.xm.common.core.uitls.DateUtil.getLocalDateTime;
//
///**
// * @author liheng
// * @version v1.0
// * @date 2021/6/28 14:20
// */
//@Repository
//public class RecordDaoImpl implements RecordDao {
//
//
//    @Resource
//    private MongoTemplate mongoTemplate;
//
////    /**
////     * 根据DTO参数查询原话记录
////     *
////     * @param recordSearchDTO 原话记录查询DTO
////     * @return List<RecordEntity> 原话记录列表
////     * @author jy.zhao
////     * @date 2021/5/13 13:55
////     * 弃用原因：与下面方法功能一致
////     * @see RecordDao#listRecordContent
////     **/
////    @Override
////    @Deprecated
////    public List<RecordDO> listRecord(RecordSearchDTO recordSearchDTO) {
////        Query query = recordSearchToQuery(recordSearchDTO);
////        query.fields().include(CONTENT);
////        return mongoTemplate.find(query, RecordDO.class, TXTANLS_RECORD);
////    }
//
//
//    /**
//     * 根据DTO参数查询原话记录Id
//     *
//     * @param recordSearchDTO 原话记录查询DTO
//     * @return List<RecordEntity> 原话记录列表
//     * @author jy.zhao
//     * @date 2021/5/13 13:55
//     **/
//    @Override
//    public List<String> listRecordIds(RecordSearchDTO recordSearchDTO) {
//        Query query = recordSearchToQuery(recordSearchDTO);
//        query.fields().include(_ID);
//        List<Map> recordList = mongoTemplate.find(query, Map.class, TXTANLS_RECORD);
//        return recordList.stream().map(item -> item.get(_ID).toString()).collect(Collectors.toList());
//    }
//
//
//    /**
//     * 统计原话记录数
//     *
//     * @param recordSearchDTO 查询条件
//     * @return 原话记录数
//     */
//    @Override
//    public Long countRecord(RecordSearchDTO recordSearchDTO) {
//        Query query = this.recordSearchToQuery(recordSearchDTO);
//        if (CollUtil.isNotEmpty(recordSearchDTO.getKeywords())) {
//            String regex = String.join(OR, recordSearchDTO.getKeywords());
//            query.addCriteria(Criteria.where(CONTENT).regex(regex));
//        }
//        return mongoTemplate.count(query, RecordDO.class, TXTANLS_RECORD);
//    }
//
////    @Override
//    public Long countRecordWithRegex(RecordSearchDTO recordSearchDTO, String regex) {
//        Query query = this.recordSearchToQuery(recordSearchDTO);
//        query.addCriteria(Criteria.where(CONTENT).regex(regex));
//        return mongoTemplate.count(query, RecordDO.class, TXTANLS_RECORD);
//    }
//
//
//    /**
//     * 构造查询条件方法，根据projectId。fieldIdList和periodTime三个参数查询
//     *
//     * @param recordSearchDTO
//     * @return
//     */
//    private Query recordSearchToQuery(RecordSearchDTO recordSearchDTO) {
//        Query query = new Query();
//        PeriodTimeDTO periodTime = recordSearchDTO.getPeriodTime();
//        query.addCriteria(Criteria.where(PROJECT_ID).is(new ObjectId(recordSearchDTO.getProjectId())));
//        query.addCriteria(Criteria.where(FIELD_ID).in(CommonUtils.stringToObjectId(recordSearchDTO.getFieldIds())));
//        if (!ObjectUtils.isEmpty(recordSearchDTO.getPeriodTime())) {
//            Criteria timeCriteria = Criteria.where(RECORD_TIME);
//            if (!ObjectUtils.isEmpty(recordSearchDTO.getPeriodTime().getStartTime())
//                    && !ObjectUtils.isEmpty(recordSearchDTO.getPeriodTime().getEndTime())) {
//                timeCriteria.gte(DateUtil.formatString(periodTime.getStartTime()));
//                timeCriteria.lte(DateUtil.formatString(periodTime.getEndTime()));
//                query.addCriteria(timeCriteria);
//            }
//        }
//        return query;
//    }
//
//
//    /**
//     * 原话记录保存
//     *
//     * @param recordEntity 需保存的原话记录
//     * @author gy.liu
//     * @date 2021/5/14
//     */
//    @Override
//    public RecordDO insertRecord(RecordDO recordEntity) {
//        recordEntity.setCreatedDate(DateUtil.getMongoDate());
//        recordEntity.setUpdatedDate(DateUtil.getMongoDate());
//        return mongoTemplate.save(recordEntity);
//    }
//
//    /**
//     * 查询原话对应的情感，并对其结果进行聚合处理
//     *
//     * @param recordSearchDTO 原话查询参数
//     * @return List<String>  原话情感分组结果
//     * @author jy.zhao
//     * @date 2021/5/14 13:32
//     **/
//    @Override
//    public Map<String, Integer> listRecordSentisGroupBySenti(RecordSearchDTO recordSearchDTO) {
//        PeriodTimeDTO periodTime = recordSearchDTO.getPeriodTime();
//        Criteria criteria = Criteria.where(PROJECT_ID).is(new ObjectId(recordSearchDTO.getProjectId()))
//                .and(FIELD_ID).in(CommonUtils.stringToObjectId(recordSearchDTO.getFieldIds()))
//                .and(RECORD_TIME).gte(DateUtil.formatString(periodTime.getStartTime())).lte(DateUtil.formatString(periodTime.getEndTime()));
//        GroupOperation groupOperation = Aggregation.group(recordSearchDTO.getGroupBy()).count().as("count").first(SENTI).as(SENTI);
//
//        Aggregation aggr = Aggregation.newAggregation(Aggregation.match(criteria), groupOperation);
//        AggregationResults<RecordSentiDTO> results = mongoTemplate.aggregate(aggr, TXTANLS_RECORD, RecordSentiDTO.class);
//        List<RecordSentiDTO> recordSentiDTOS = results.getMappedResults();
//        if (recordSentiDTOS.isEmpty()) {
//            return null;
//        }
//        return recordSentiDTOS.stream().filter(item -> Validator.isNotEmpty(item.getCount())).collect(Collectors.toMap(RecordSentiDTO::getSenti, RecordSentiDTO::getCount, (v1, v2) -> v2));
//    }
//
//    /**
//     * 查询原话记录的内容
//     *
//     * @param recordSearchDTO 查询条件
//     * @return List<String> 原话记录内容
//     * @author jy.zhao
//     * @date 2021/5/14 16:08
//     **/
//    @Override
//    public List<String> listRecordContent(RecordSearchDTO recordSearchDTO) {
//        Query query = recordSearchToQuery(recordSearchDTO);
//        query.fields().include(CONTENT);
//        List<Map> recordEntities = mongoTemplate.find(query, Map.class, TXTANLS_RECORD);
//        return recordEntities.stream().filter(item -> Validator.isNotEmpty(item.get(CONTENT))).map(item -> item.get(CONTENT).toString()).collect(Collectors.toList());
//    }
//
//    /**
//     * 根据关键词查询原话记录的Id
//     * 使用时注意 返回类型为{"_id": {"$oid": "60506b5e528324003c4bfa88"}}。
//     * 为了性能，直接使用字符串接收，对结果不影响
//     *
//     * @param recordSearchDTO 查询条件
//     * @return List<String> 原话记录的Id数组
//     * @author jy.zhao
//     * @date 2021/5/14 16:08
//     **/
//    @Override
//    public Set<String> listRecordIdByKeywords(RecordSearchDTO recordSearchDTO) {
//        Query query = getRecordByKeywordParam(recordSearchDTO);
//        query.fields().include(_ID);
//        // 使用实体接收时，需要把实体映射为id。性能较差。所以直接使用字符串接收，目前对结果不影响
//        List<String> recordIds = mongoTemplate.find(query, String.class, TXTANLS_RECORD);
//        return new HashSet<>(recordIds);
//    }
//
//    /**
//     * 关键字查询参数拼接
//     *
//     * @param recordSearchDTO 原话记录查询条件
//     * @return Query query对象
//     * @author jy.zhao
//     * @date 2021/5/25 15:39
//     **/
//    private Query getRecordByKeywordParam(RecordSearchDTO recordSearchDTO) {
//        Query query = new Query();
//        PeriodTimeDTO periodTime = recordSearchDTO.getPeriodTime();
//        Criteria criteria = Criteria.where(PROJECT_ID).is(new ObjectId(recordSearchDTO.getProjectId()))
//                .and(FIELD_ID).in(CommonUtils.stringToObjectId(recordSearchDTO.getFieldIds()))
//                .and(RECORD_TIME).gte(DateUtil.formatString(periodTime.getStartTime())).lte(DateUtil.formatString(periodTime.getEndTime()));
//        // 根据关键词查询  '$or': [{'content': {'$regex': ks}} for ks in keywords],
////        List<String> keywords = recordSearchDTO.getKeywords();
////        Criteria[] criteriaArr = new Criteria[keywords.size()];
////        for (int i = 0; i < keywords.size(); i++) {
////            criteriaArr[i] = Criteria.where(CONTENT).regex(keywords.get(i));
////        }
////        criteria.orOperator(criteriaArr);
//        query.addCriteria(criteria);
//        String regex = String.join(OR, recordSearchDTO.getKeywords());
//        query.addCriteria(Criteria.where(CONTENT).regex(regex));
//        return query;
//    }
//
//    /**
//     * 根据关键词查询原话记录的数量
//     *
//     * @param recordSearchDTO 查询条件
//     * @return Long 原话记录数量
//     * @author jy.zhao
//     * @date 2021/5/14 16:08
//     **/
//    @Override
//    public Long countRecordByKeyword(RecordSearchDTO recordSearchDTO) {
//        Query query = getRecordByKeywordParam(recordSearchDTO);
//        return mongoTemplate.count(query, String.class, TXTANLS_RECORD);
//    }
//
//    /**
//     * 根据项目id查找原话记录的最小时间
//     *
//     * @param projectId 项目id
//     * @return LocalDateTime 找不到时返回null
//     * @author jy.zhao
//     * @date 2021/5/24 15:07
//     **/
//    @Override
//    public LocalDateTime getMinRecordTimeByProject(String projectId) {
//        Query query = new Query();
//        query.addCriteria(Criteria.where(PROJECT_ID).is(new ObjectId(projectId)));
//        query.with(Sort.by(Sort.Direction.ASC, RECORD_TIME));
//        RecordDO record = mongoTemplate.findOne(query, RecordDO.class, TXTANLS_RECORD);
//        if (Validator.isNull(record) || Validator.isEmpty(record.getRecordTime())) {
//            return null;
//        }
//        LocalDateTime localDateTime;
//        try {
//            localDateTime = getLocalDateTime(record.getRecordTime());
//        } catch (Exception dateTimeParseException) {
//            localDateTime = LocalDateTime.of(LocalDate.EPOCH, LocalTime.MIN);
//        }
//        return localDateTime;
//    }
//
//    /**
//     * 获取当前文本分析项目已有原话记录中的最大时间
//     *
//     * @param projectId projectId
//     * @author liheng
//     * @date 2021/5/14 11:23
//     */
//    @Override
//    public LocalDateTime getMaxTime(String projectId) {
//        Query query = Query.query(Criteria.where(PROJECT_ID).is(new ObjectId(projectId)));
//        query.with(Sort.by(Sort.Direction.DESC, RECORD_TIME));
//        RecordDO record = mongoTemplate.findOne(query, RecordDO.class, TXTANLS_RECORD);
//        if (ObjectUtil.isNull(record)) {
//            return null;
//        }
//        // 外部异常捕获
//        return getLocalDateTime(record.getRecordTime());
//    }
//
//    /**
//     * 分页查询原话记录
//     *
//     * @param pageRecordDTO
//     * @return
//     * @author liheng
//     * @date 2021/6/4 18:06
//     */
//    @Override
//    public PageDTO<RecordDO> pageRecord(PageRecordDTO pageRecordDTO) {
//        PageParam pageParam = pageRecordDTO.getPageParam();
//        Query query = new Query(Criteria.where(PROJECT_ID).is(new ObjectId(pageRecordDTO.getProjectId())));
//        if (!ObjectUtils.isEmpty(pageRecordDTO.getStartTime())) {
//            Criteria gte = Criteria.where(RECORD_TIME).gte(DateUtil.formatString(pageRecordDTO.getStartTime()));
//            query.addCriteria(gte);
//            if (!ObjectUtils.isEmpty(pageRecordDTO.getEndTime())) {
//                gte.lte(DateUtil.formatString(pageRecordDTO.getEndTime()));
//            }
//        }
//        if (!ObjectUtils.isEmpty(pageRecordDTO.getFieldId())) {
//            query.addCriteria(Criteria.where(FIELD_ID).is(new ObjectId(pageRecordDTO.getFieldId())));
//        } else if (!CollectionUtils.isEmpty(pageRecordDTO.getFieldIds())) {
//            query.addCriteria(Criteria.where(FIELD_ID).in(CommonUtils.stringToObjectId(pageRecordDTO.getFieldIds())));
//        }
//        if (!ObjectUtils.isEmpty(pageRecordDTO.getSenti())) {
//            query.addCriteria(Criteria.where(SENTI).is(pageRecordDTO.getSenti()));
//        }
//
//        if (!ObjectUtils.isEmpty(pageRecordDTO.getWord()) || !ObjectUtils.isEmpty(pageRecordDTO.getTopicKeyword())) {
//            Criteria criteria = new Criteria();
//            if (!ObjectUtils.isEmpty(pageRecordDTO.getWord())) {
//                criteria = criteria.andOperator(Criteria.where(CONTENT).regex(pageRecordDTO.getWord()));
//            }
//            if (!ObjectUtils.isEmpty(pageRecordDTO.getTopicKeyword())) {
//                criteria = criteria.and(CONTENT).regex(pageRecordDTO.getTopicKeyword());
//            }
//            query.addCriteria(criteria);
//        }
//
//        long count = mongoTemplate.count(query, RecordDO.class);
//        if (!ObjectUtils.isEmpty(pageParam)) {
//            int skipSize = pageParam.getPage() * pageParam.getSize();
//            query.skip(skipSize);
//            query.limit(pageParam.getSize());
//        }
//        query.with(Sort.by(Sort.Direction.DESC, RECORD_TIME));
//        List<RecordDO> list = mongoTemplate.find(query, RecordDO.class);
//        return new PageDTO<>(list, count);
//    }
//
//    @Override
//    public RecordDO getRecordByProjectId(String projectId) {
//        Query query = new Query();
//        query.addCriteria(Criteria.where(PROJECT_ID).is(new ObjectId(projectId)));
//        return mongoTemplate.findOne(query, RecordDO.class);
//    }
//
//
//    /**
//     * 删除分析项目下的全部话题
//     *
//     * @param projectId 项目id
//     * @return The result of a delete operation
//     * @author XiaoYunSong <ys.xiao@idiaoyan.cn>
//     * @date 2021/5/21 14:27
//     */
//    @Override
//    public int deleteProjectAllRecord(String projectId) {
//        Query query = new Query();
//        query.addCriteria(Criteria.where(PROJECT_ID).is(new ObjectId(projectId)));
//        DeleteResult deleteResult= mongoTemplate.remove(query, TXTANLS_RECORD);
//        return (int) deleteResult.getDeletedCount();
//    }
//
//    // ================== 异步训练用 ==================
//
//
//    @Override
//    public long countProjectAllRecord(String projectId) {
//        Query query = new Query();
//        query.addCriteria(Criteria.where(PROJECT_ID).is(new ObjectId(projectId)));
//        return mongoTemplate.count(query, RecordDO.class, TXTANLS_RECORD);
//    }
//
//    @Override
//    public long countProjectFieldRecord(String projectId, String fieldId) {
//        Query query = new Query();
//        query.addCriteria(Criteria.where(PROJECT_ID).is(new ObjectId(projectId)));
//        query.addCriteria(Criteria.where(FIELD_ID).is(new ObjectId(fieldId)));
//        return mongoTemplate.count(query, RecordDO.class, TXTANLS_RECORD);
//    }
//
//    @Override
//    public String findMaxCollectionTime(String projectId, String fieldId) {
//        String key = "maxQuantity";
//        MatchOperation match = Aggregation.match(new Criteria(PROJECT_ID).is(new ObjectId(projectId)).and(FIELD_ID).is(new ObjectId(fieldId)));
//        GroupOperation group = Aggregation.group("None").max(COLLECTION_TIME).as(key);
//        Aggregation aggregation = Aggregation.newAggregation(match, group);
//        AggregationResults<Map> max = mongoTemplate.aggregate(aggregation, TXTANLS_RECORD, Map.class);
//        List<Map> result = max.getMappedResults();
//        if (CollectionUtils.isEmpty(result)) {
//            return "";
//        } else {
//            return result.get(0).get(key).toString();
//        }
//    }
//
//    @Override
//    public String findMaxCreatedDt(String projectId, String fieldId) {
//        String key = "maxQuantity";
//        MatchOperation match = Aggregation.match(new Criteria(PROJECT_ID).is(new ObjectId(projectId)).and(FIELD_ID).is(new ObjectId(fieldId)));
//        GroupOperation group = Aggregation.group("None").max(CREATED_DT).as(key);
//        Aggregation aggregation = Aggregation.newAggregation(match, group);
//        AggregationResults<Map> max = mongoTemplate.aggregate(aggregation, TXTANLS_RECORD, Map.class);
//        List<Map> result = max.getMappedResults();
//        if (CollectionUtils.isEmpty(result)) {
//            return "";
//        } else {
//            return result.get(0).get(key).toString();
//        }
//    }
//
////    @Override
////    public String findMaxCollectionId(String projectId, String fieldId) {
////        Query query = new Query();
////        query.addCriteria(Criteria.where(PROJECT_ID).is(new ObjectId(projectId)));
////        query.addCriteria(Criteria.where(FIELD_ID).is(new ObjectId(fieldId)));
////        query.with(Sort.by(Sort.Direction.DESC, CREATED_DT));
////        RecordDO record = mongoTemplate.findOne(query, RecordDO.class, TXTANLS_RECORD);
////        if (Objects.isNull(record) || ObjectUtils.isEmpty(record.getCollectionId())) {
////            return null;
////        }
////        return record.getCollectionId();
////    }
//}
